<?php


namespace EchoPHP\Support\Traits;

use BadMethodCallException;
use Closure;
use ReflectionClass;
use ReflectionMethod;

/**
 * 宏方法  所谓宏即批处理逻辑
 * Class Macroable
 * @package EchoPHP\Support\Traits
 */
trait Macroable {

    /**
     * 已注册宏集合
     * @var array
     */
    protected static $macros = [];

    /**
     * 注册一个自定义宏
     * @param $name
     * @param $macro
     */
    public static function macro($name, $macro) {
        static::$macros[$name] = $macro;
    }

    /**
     * 将另一个对象植入当前类
     * @param $mixin
     * @param bool $replace
     * @throws \ReflectionException
     */
    public static function mixin($mixin, $replace = true) {
        $methods = (new ReflectionClass($mixin))->getMethods(
            ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
        );
        foreach ($methods as $method) {
            if ($replace || !static::hasMacro($method->name)) {
                $method->setAccessible(true);
                static::macro($method->name, $method->invoke($mixin));
            }
        }
    }

    /**
     * 判断宏是否已经注册
     * @param $name
     * @return bool
     */
    public static function hasMacro($name) {
        return isset(static::$macros[$name]);
    }

    public static function __callStatic($method, $parameters) {
        if (!static::hasMacro($method)) {
            throw new BadMethodCallException(sprintf(
                'method %s::%s does not exist', static::class, $method
            ));
        }

        $macros = static::$macros[$method];

        if ($macros instanceof Closure) {
            return call_user_func_array(Closure::bind($macros, null, static::class), $parameters);
        }

        return call_user_func_array($macros, $parameters);
    }

    public function __call($method, $parameters) {
        if (!static::hasMacro($method)) {
            throw new BadMethodCallException(sprintf(
                'Method %s::%s does not exist.', static::class, $method
            ));
        }

        $macro = static::$macros[$method];

        if ($macro instanceof Closure) {
            return call_user_func_array($macro->bindTo($this, static::class), $parameters);
        }

        return call_user_func_array($macro, $parameters);
    }
}